package com.alon.spring01.study.queue;

import lombok.Data;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @program: spring01
 * @description: 数据延迟实现实例，用于包装具体的实例转型
 * @author: yulongguang
 * @create: 2019-09-29 20:30
 **/
@Data
public class ItemDelayed<T> implements Delayed {
    /**
     * 默认延迟30分钟
     */
    private final static Long DELAY = 30 * 60 * 1000L;
    /**
     * 数据id
     */
    private Long dataId;
    /**
     * 开始时间
     */
    private long startTime;
    /**
     * 过期时间
     */
    private long expire;
    /**
     * 创建时间
     */
    private Date now;
    /**
     * 泛型 data
     */
    private T date;

    public ItemDelayed(Long dataId, long startTime, long secondsDelay) {
        super();
        this.dataId = dataId;
        this.startTime = startTime;
        this.expire = startTime + (secondsDelay * 1000);
        this.now = new Date();
    }

    public ItemDelayed(Long dataId, long startTime) {
        super();
        this.dataId = dataId;
        this.startTime = startTime;
        this.expire = startTime + DELAY;
        this.now = new Date();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }
}
